import { Suspense, lazy, useEffect, useState } from "react";
import {
  Navigate,
  useLocation,
  useNavigate,
  Routes,
  Route,
} from "react-router-dom";
import { deepAddKey } from "@/utils/tools";
import KeepAlive from "react-activation";

const NotFound = lazy(() => import("@pages/404"));
const Login = lazy(() => import("@pages/Login"));
const BasicLayout = lazy(() => import("@layout/index"));
const Home = lazy(() => import("@/pages/Home"));
const UserList = lazy(() => import("@/pages/User/List"));
const Account = lazy(() => import("@/pages/System/Account"));
const Menu = lazy(() => import("@/pages/System/Menu"));
const Role = lazy(() => import("@/pages/System/Role"));

const defaultRoutes: any[] = [
  {
    path: "/",
    element: <Navigate to="/login" />,
  },
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "/notfound",
    element: <NotFound />,
  },
  {
    path: "*",
    element: <Navigate to="/notfound" />,
  },
];
// level 0: 目录 1：菜单 2：按钮 3：接口
export const asyncRoutes = [
  {
    name: "home",
    path: "/home",
    meta: {
      title: "首页",
      level: 1,
    },
    element: <BasicLayout />,
    children: [
      {
        name: "",
        path: "",
        meta: {},
        element: <Home />,
      },
    ],
  },
  {
    name: "user",
    path: "/user",
    meta: {
      title: "用户管理",
      level: 0,
    },
    element: <BasicLayout />,
    children: [
      {
        name: "user-list",
        path: "list",
        meta: {
          title: "用户列表",
          level: 1,
        },
        element: <UserList />,
      },
    ],
  },
  {
    name: "system",
    path: "/system",
    meta: {
      title: "系统管理",
      level: 0,
    },
    element: <BasicLayout />,
    children: [
      {
        name: "system-account",
        path: "account",
        meta: {
          title: "账号管理",
          level: 1,
        },
        element: <Account />,
      },
      {
        name: "system-menu",
        path: "menu",
        meta: {
          title: "菜单管理",
          level: 1,
        },
        element: <Menu />,
      },
      {
        name: "system-role",
        path: "role",
        meta: {
          title: "角色管理",
          level: 1,
        },
        element: <Role />,
      },
    ],
  },
];

const routeConfig = deepAddKey([...defaultRoutes, ...asyncRoutes]);
const routerBeforeEach = (to?: any, _from?: any, next?: any) => {
  const isLoginState = localStorage.getItem("user");
  if (isLoginState) {
    if (to.pathname === "/login") {
      next("/home");
    }
  } else {
    next("/login");
  }
};
const routeMap = (routes: any[]) => {
  return routes.map((route) => {
    if (!route?.children?.length) {
      return (
        <Route
          path={route.path}
          element={
            <KeepAlive cacheKey={route.diff_key} name={route.diff_key}>
              <Suspense fallback={<div>Loading...</div>}>
                {route.element}
              </Suspense>
            </KeepAlive>
          }
          key={route.diff_key}
        />
      );
    }
    return (
      <Route
        path={route.path}
        element={
          <Suspense fallback={<div>Loading...</div>}>{route.element}</Suspense>
        }
        key={route.diff_key}
      >
        {routeMap(route.children)}
      </Route>
    );
  });
};
export default function BasicRoutes() {
  const location = useLocation();
  const [preRoute, setPreRoute] = useState<any>(null);
  const navigator = useNavigate();
  useEffect(() => {
    routerBeforeEach(location, preRoute, navigator);
    setPreRoute(location);
  }, [location.pathname]);
  // return useRoutes(routeConfig); // 写法1
  return <Routes>{routeMap(routeConfig)}</Routes>; // 写法2
}
